//
//  ZZCHomeController.m
//  ZZC-Finance
//
//  Created by mac on 2017/5/21.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "ZZCHomeController.h"
#import "PWBannerView.h"
#import "SMPageControl.h"
#import "ZZCintroduceController.h"
#import "ZZCCommonProblemController.h"
#import "ZZCOwnPropertyController.h"
#import "ZZCMeUbiViewController.h"
#import "ZZCJoinController.h"
#import "SYCitySelectionController.h"
#import "ZZCAdvertisement.h"
#import "ZZCSearchController.h"
#import "ZZCAssetStatusController.h"
#import "ZZCAssetWaitController.h"
#import "ZZCAssetCashController.h"
#import "ZZCMovablePropertyController.h"
#import "ZZCImmovablePropertyController.h"
#import "ZZCLoginController.h"
#import "ZZCLabourController.h"
#import "ZZCReleaseController.h"
#import "ZZCMessageController.h"
#import "ZZCReportPayControllerViewController.h"
#import "ZZCBanerWebController.h"
@interface ZZCHomeController ()<UITextFieldDelegate,PWBannerViewDelegate>
@property (nonatomic, strong) UITextField *searchBar;
@property (nonatomic, strong, null_resettable) SMPageControl *pageControl;
@property (nonatomic, strong, null_resettable) PWBannerView  *banner;
@property (nonatomic, strong) UIButton *leftBtn;
@property (nonatomic, strong) NSArray *adArray;
@property (nonatomic ,strong) ZZCLoginController *loginVC;
@property (assign, nonatomic) BOOL isLogin;//判断是否登录
@property (copy,   nonatomic) NSString *WARN;

//@property (retain, nonatomic) NSMutableArray *urlArray;
@end

@implementation ZZCHomeController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    _searchBar.hidden = NO;
    IQKeyboardManager *iq = [IQKeyboardManager sharedManager];
    iq.enableAutoToolbar = YES;
    _searchBar.text = @"";
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"isLogin"]) {
        [self reloadSucceedData];
    }

}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    _searchBar.hidden = YES;
}

- (void)viewDidLayoutSubviews {
    self.banner.frame = CGRectMake(0, 0, ZZCScreenW, self.bannerView.frame.size.height);
    self.pageControl.frame = CGRectMake(0, self.bannerView.frame.size.height-20, ZZCScreenW, 10);
}
- (void)viewDidLoad {
    [super viewDidLoad];

    if(![[NSUserDefaults standardUserDefaults] floatForKey:@"appchacha"]){
        [[NSUserDefaults standardUserDefaults] setFloat:0 forKey:@"appchacha"];
            NSLog(@"第一次启动设为0");
    }
    float chacha = [[NSUserDefaults standardUserDefaults] floatForKey:@"appchacha"];
    chacha += 0.02;
    [[NSUserDefaults standardUserDefaults] setFloat:chacha forKey:@"appchacha"];

    self.isLogin = NO;
    self.navigationItem.title = @"";
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self requestAdvertisementData];
    //监听登录成功的通知
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadSucceedData) name:@"loginSucceed" object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadSucceedData) name:@"updetaMeInfo" object:nil];
    //退出登录的通知
}

//请求广告数据
- (void)requestAdvertisementData {
    NSDictionary *dict = @{@"location_id":@(4)};
    NSString *sign = [ZZCRequest getSignWithDict:dict];
    sign = [NSString md5:sign];
    NSDictionary *param = @{@"timestamp":[NSString timeStr],@"sign":sign,@"location_id":@(4)};
    [[ZZCRequest sharedNetworkTools] POST:ZZCURL_API_INDEX parameters:param finished:^(id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            ZZCLog(@"失败-%@",error);
        }else {
            NSLog(@"%@",responseObject);
            self.adArray = [ZZCAdvertisement mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"list"]];
//            NSMutableDictionary *dic = responseObject[@"data"][@"list"];
//            for (NSArray *arr in dic) {
//                [self.urlArray addObject:arr[2]];
//            }
            [self createUI];
            [self settingNav];
        }
    }];
}
#pragma mark - 设置导航栏
- (void)settingNav{
    self.leftBtn = [[UIButton alloc]init];
    [self.leftBtn setTitle:@"深圳" forState:UIControlStateNormal];
    [self.leftBtn setImage:[UIImage imageNamed:@"下拉icon"] forState:UIControlStateNormal];
    self.leftBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -30, 0, 0);
    self.leftBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -85);
    self.leftBtn.size = CGSizeMake(52, 22);
    self.leftBtn.titleLabel.font = TextFont(15);
    [self.leftBtn addTarget:self action:@selector(addressClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.leftBtn];
    
    //设置搜索对话框
    _searchBar = [[UITextField alloc]init];
    
    _searchBar.frame = CGRectMake(85, 10, ZZCScreenW-120, 26);
    _searchBar.centerY = self.leftBtn.centerY;
    _searchBar.delegate = self;
    _searchBar.layer.cornerRadius = 13;
    _searchBar.placeholder = @"搜索你想要的商品";
    _searchBar.font = TextFont(13);
    _searchBar.layer.masksToBounds = YES;
    UIView *blankView = [[UIView alloc] initWithFrame:CGRectMake(_searchBar.frame.origin.x,_searchBar.frame.origin.y,35.0, _searchBar.frame.size.height)];
    _searchBar.leftView = blankView;
    _searchBar.leftViewMode =UITextFieldViewModeAlways;
    _searchBar.backgroundColor = Color(239, 240, 241, 1);
    _searchBar.font = [UIFont fontWithName:@"Arial" size:14.0f];
    [self.navigationController.navigationBar addSubview:_searchBar];
    
    UIImageView *seachImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"搜索icon"]];
    [_searchBar addSubview:seachImg];
    [seachImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_searchBar.mas_centerY);
        make.right.equalTo(_searchBar.mas_left).offset(30);
    }];
    
    
}
//设置点击搜索对话框事件

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    NSLog(@" 搜索对话框被点击");
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"isLogin"]) {
        [self gobackLogin];
    } else {
        ZZCSearchController *searchVC = [ZZCSearchController new];
        [self.navigationController pushViewController:searchVC animated:YES];
    }
    return NO;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

//地址按钮
- (void)addressClick {
    ZZCLog(@"地址按钮点击");
    SYCitySelectionController *city = [SYCitySelectionController new];
    city.openLocation = YES;
    city.currentCityName = @"深圳";
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    city.backView = back;
    [self.navigationController pushViewController:city animated:YES];
    city.selectCity = ^(NSString *city) {
        ZZCLog(@"%@", city);
        [self.leftBtn setTitle:city forState:UIControlStateNormal];
    };
}

#pragma mark - UI
- (void)createUI {
    NSMutableArray *imgArr = [NSMutableArray array];
    for (ZZCAdvertisement *ad in self.adArray) {
        [imgArr addObject:ad.img_src];
    }
    _banner.imageURLs = imgArr;
    _pageControl.numberOfPages = self.adArray.count;
    [self.bannerView addSubview:self.banner];
    [self.banner addSubview:self.pageControl];
}



#pragma mark - PWBannerViewdelegate方法
- (void)bannerView:(PWBannerView *)bannerView didSelectAtIndex:(NSInteger)idx {
    //可以在这里做页面跳转
    ZZCLog(@"你点击了%ld",(long)idx);
    ZZCBanerWebController *vc = [ZZCBanerWebController new];
//    vc.urlstr = _urlArray[idx-1];
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)bannerView:(PWBannerView *)bannerView nextPageAtIndex:(NSInteger)idx {
    self.pageControl.currentPage = idx;
}

#pragma mark - 项目介绍按钮点击
- (IBAction)pbDescBtnClick:(UIButton *)sender {
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"isLogin"]) {
        [self gobackLogin];
    } else {
        ZZCintroduceController *intr = [ZZCintroduceController new];
        [self.navigationController pushViewController:intr animated:YES];
    }
}
// 常见问题按钮点击
- (IBAction)qusetionBtnClick:(UIButton *)sender {
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"isLogin"]) {
        [self gobackLogin];
    } else {
        ZZCCommonProblemController *common = [ZZCCommonProblemController new];
        [self.navigationController pushViewController:common animated:YES];
    }
}
// 代理合作按钮点击
- (IBAction)delegateBtnClick:(UIButton *)sender {
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"isLogin"]) {
        [self gobackLogin];
    } else {
        ZZCJoinController *join = [ZZCJoinController new];
        [self.navigationController pushViewController:join animated:YES];
    }
}
// 上报资产按钮点击
- (IBAction)propertyBtnClick:(UIButton *)sender {
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"isLogin"]) {
        [self gobackLogin];
    } else {
        ZZCAssetStatusController *assetStatus = [ZZCAssetStatusController new];
        assetStatus.title = @"上报资产";
        [self.navigationController pushViewController:assetStatus animated:YES];
    }
}

#pragma mark - 我的资产按钮点击
- (IBAction)myPropertyBtnClick:(UIButton *)sender {
    ZZCOwnPropertyController *own = [ZZCOwnPropertyController new];
//    own.isLogin = YES;
    NSString *token = ZZCNSUserDefaults(@"token");
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"isLogin"]) {
        [self gobackLogin];
    }else {
        [self.navigationController pushViewController:own animated:YES];
    }
}

// 待评估资产按钮点击
- (IBAction)waitEvaluateBtnClick:(UIButton *)sender {
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"isLogin"]) {
        [self gobackLogin];
    } else {
        ZZCAssetWaitController *aWait = [ZZCAssetWaitController new];
        aWait.title = @"待评估资产";
        [self.navigationController pushViewController:aWait animated:YES];
    }
}

// 我的U币按钮点击
- (IBAction)myUBBtnClick:(UIButton *)sender {
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"isLogin"]) {
        [self gobackLogin];
    } else {
        ZZCMeUbiViewController *me = [ZZCMeUbiViewController new];
        [self.navigationController pushViewController:me animated:YES];
    }
}

// 劳务合作按钮点击
- (IBAction)appliedPropertyBtnClick:(id)sender {
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"isLogin"]) {
        [self gobackLogin];
    } else {
//        ZZCTempController *Temp = [ZZCTempController new];
//        Temp.title = @"应用资产";
//        [self.navigationController pushViewController:Temp animated:YES];
        ZZCLabourController *lab = [ZZCLabourController new];
        [self.navigationController pushViewController:lab animated:YES];
    }
}

// 发布消息
- (IBAction)receiptBtnClick:(UIButton *)sender {
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"isLogin"]) {
        [self gobackLogin];
    } else {
        ZZCReleaseController *release = [ZZCReleaseController new];
        release.title = @"发布消息";
        [self.navigationController pushViewController:release animated:YES];
    }
}

// 信息中心
- (IBAction)IOUBtnClick:(UIButton *)sender {
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"isLogin"]) {
        [self gobackLogin];
    } else {
        ZZCMessageController *message = [ZZCMessageController new];
        message.title = @"信息中心";
        [self.navigationController pushViewController:message animated:YES];
    }
}

// 资产变现按钮点击/改应付资产
- (IBAction)cashBtnClick:(UIButton *)sender {
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"isLogin"]) {
        [self gobackLogin];
    } else {
        ZZCReportPayControllerViewController *VC = [ZZCReportPayControllerViewController new];
        [self.navigationController pushViewController:VC animated:YES];
    }
}

// 不动产按钮点击/改应收资产
- (IBAction)realEstateBtnClick:(UIButton *)sender {
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"isLogin"]) {
        [self gobackLogin];
    } else {
//        ZZCImmovablePropertyController *VC = [ZZCImmovablePropertyController new];
//        VC.title = @"不动产";
//        [self.navigationController pushViewController:VC animated:YES];
        ZZCAssetStatusController *assetStatus = [ZZCAssetStatusController new];
        assetStatus.title = @"上报资产";
        [self.navigationController pushViewController:assetStatus animated:YES];

    }
}

// 动产按钮点击/改可支付资产（资产变现）
- (IBAction)movablesBtnClick:(UIButton *)sender {
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"isLogin"]) {
        [self gobackLogin];
    } else {
//        ZZCMovablePropertyController *VC = [ZZCMovablePropertyController new];
//        VC.title = @"动产";
//        [self.navigationController pushViewController:VC animated:YES];
        ZZCAssetCashController *VC = [ZZCAssetCashController new];
        VC.title = @"资产变现";
        [self.navigationController pushViewController:VC animated:YES];

    }
}
//返回登陆界面
- (void)gobackLogin {
    ZZCLoginController *LoginVC = [ZZCLoginController new];
    [self.navigationController pushViewController:LoginVC animated:YES];
}
- (PWBannerView *)banner {//广告位
    if (!_banner) {
        _banner = [[PWBannerView alloc] init];
        _banner.delegate = self;

    }
    return _banner;
}
//- (NSMutableArray *)urlArray {
//    if (_urlArray == nil) {
//        _urlArray = [NSMutableArray array];
//    }
//    return _urlArray;
//
//}

- (SMPageControl *)pageControl {
    if (!_pageControl) {
        _pageControl = [[SMPageControl alloc]initWithFrame:CGRectMake(0, ZZCScreenW*(26/75.0)-20, ZZCScreenW, 20)];
    }
    return _pageControl;
}

- (NSArray *)adArray {
    if (_adArray == nil) {
        _adArray = [NSArray array];
    }
    return _adArray;
}
//登录成功后刷新数据源
- (void)reloadSucceedData {
    NSString *token = ZZCNSUserDefaults(@"token");
    NSDictionary *dict = @{@"token":token};
    NSString *sign = [ZZCRequest getSignWithDict:dict];
    sign = [NSString md5:[sign lowercaseString]];
    NSDictionary *param = @{@"timestamp":[NSString timeStr],@"sign":sign,@"token":token};
    [[ZZCRequest sharedNetworkTools] POST:ZZCURL_API_PERSONAL parameters:param finished:^(id  _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            ZZCLog(@"-%@",responseObject);
            if ([responseObject[@"code"] isEqual:@(301)]) {
                _WARN = responseObject[@"msg"];
                NSLog(@"账号已在别的设备登录");
                [self alertView];
                
            }
        }
    }];
}
- (void)alertView
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:_WARN  message:@"请重新登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.alertViewStyle = UIAlertViewStyleDefault;
    [alert show];
}
//监听点击事件 代理方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *btnTitle = [alertView buttonTitleAtIndex:buttonIndex];
    if ([btnTitle isEqualToString:@"取消"]) {
        NSLog(@"你点击了取消");
    }else if ([btnTitle isEqualToString:@"确定"] ) {
        NSLog(@"你点击了确定");
        ZZCLoginController *login = [ZZCLoginController new];
        [self.navigationController pushViewController:login animated:YES];
        //        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    }//https在iTunes中找，这里的事件是前往手机端App store下载微信
}

@end
